package com.wocao.framework.security.filter;

import com.wocao.commom.constant.CommonConstant;
import com.wocao.commom.constant.RedisConstant;
import com.wocao.framework.security.utils.JwtTokenUtils;
import com.wocao.system.service.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenUtils jwtTokenUtils;

    @Autowired
    private UserDetailsService userDetailServiceImpl;

    @Autowired
    private RedisService redisService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //请求头中的token,由于续命的原因这个token可能早就过期了.
        String token = request.getHeader(jwtTokenUtils.getHeader());
        if (StringUtils.isNotEmpty(token)) {
            // 从redis获取真实的token进行判断
            String newToken = redisService.get(RedisConstant.SYS_CACHE_TOKEN + token);
            if (StringUtils.isNotBlank(newToken)) {
                String username = jwtTokenUtils.getUsernameFromToken(newToken);
                if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                    UserDetails userDetails = userDetailServiceImpl.loadUserByUsername(username);
                    if (jwtTokenUtils.validateToken(newToken, userDetails)) {
                        //给使用该JWT令牌的用户进行授权
                        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                                userDetails, null, userDetails.getAuthorities());
                        //设置用户身份授权
                        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                        // 判断新的token的失效时间,如果剩余时间小于五分钟,则让其续命
                        if (jwtTokenUtils.checkTokenTime(newToken)) {
                            String refreshToken = jwtTokenUtils.refreshToken(newToken);
                            redisService.setex(RedisConstant.SYS_CACHE_TOKEN + token, refreshToken, CommonConstant.NUM_1800);
                        }
                    }
                }
            }
        }
        filterChain.doFilter(request, response);
    }

}
